<template>
  <div class="table-box">
    <!-- 必须设置row-key="question_id"，否则拖动后的顺序会出错 -->
    <ProTable
      ref="proTable"
      title="用户列表"
      :columns="columns"
      :request-api="getTableList"
      :pagination="false"
      @darg-sort="sortTable"
      row-key="question_id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('创建题目并加入题库')">
          创建题目并加入题库
        </el-button>
        <el-button
          v-auth="'delete'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #description="scope">
        <div v-html="scope.row.description"></div>
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)"> 查看 </el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)"> 编辑 </el-button>
        <el-button type="primary" link :icon="Delete" @click="delQuestion(scope.row)"> 移出考卷 </el-button>
        <el-button type="primary" link :icon="Delete" @click="delQuestionWithDestroy(scope.row)"> 移出考卷并销毁题目 </el-button>
        <el-button type="primary" link :icon="Refresh" @click="openDrawer('创建题目并加入题库', scope.row)">
          在此之前创建题目并加入题库
        </el-button>
      </template>
    </ProTable>
    <EditQuestionDrawer ref="editQuestionDrawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="editBankQuestion">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Question } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Refresh } from "@element-plus/icons-vue";
import { deleteUserApi } from "@/api/modules/user";
import {
  addQuestionWithCreateApi,
  deleteQuestionApi,
  deleteQuestionWithDestroyApi,
  getBankQuestionListApi,
  sortBankQuestionApi
} from "@/api/modules/bank_question";
import EditQuestionDrawer from "@/views/bank/editQuestionDrawer.vue";
import { updateQuestionApi } from "@/api/modules/question";

const router = useRouter();
const paths = router.currentRoute.value.path.split("/");
let bank_info = paths[paths.length - 1] as string;
let bank_object = JSON.parse(decodeURI(bank_info));
const bank_id = bank_object.bank_id;
const course_id = bank_object.course_id;
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();
// const questionList = ref<Question.QuestionInfo[]>([]);
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.bank_ids = [bank_id];
  let result = getBankQuestionListApi(newParams);
  return result;
};
// const getTableList = async (params: any) => {
//   params.bank_id = bank_id;
//   let result = await getQuestionList(params);
//   console.log(result);
//   questionList.value = result.data;
// };

// 表格配置项
const columns: ColumnProps<Question.QuestionInfo>[] = [
  { prop: "order_number", label: "题号", width: 50 },
  { type: "sort", label: "Sort", width: 50 },
  { prop: "chapter", label: "章节", width: 80 },
  { prop: "description", label: "题目说明", minWidth: 100 },
  { prop: "type_name", label: "题型", width: 80 },
  { prop: "count", label: "分值", width: 40 },
  { prop: "operation", label: "操作", width: 300 }
];

// 删除用户信息
const delQuestionWithDestroy = async (params: Question.QuestionInfo) => {
  await useHandleData(deleteQuestionWithDestroyApi, params, `删除试题`);
  proTable.value?.getTableList();
};

const delQuestion = async (params: Question.QuestionInfo) => {
  await useHandleData(deleteQuestionApi, params, `删除试题`);
  proTable.value?.getTableList();
};

// 批量删除用户信息
const batchDelete = async (id: string[]) => {
  await useHandleData(deleteUserApi, { id }, "删除所选用户信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);

// 打开 drawer(新增、查看、编辑)
const editQuestionDrawerRef = ref<InstanceType<typeof EditQuestionDrawer> | null>(null);

const openDrawer = (title: string, row: Partial<Question.QuestionInfo> = {}) => {
  if (title === "新增") {
    row = { question_id: row.question_id, order_number: row.order_number };
  }
  const params = {
    title,
    isView: true,
    row: title === "创建题目并加入题库" ? {} : { ...row },
    api: title === "创建题目并加入题库" ? addQuestionWithCreateApi : title === "编辑" ? updateQuestionApi : undefined,
    getTableList: proTable.value?.getTableList,
    // getTableList: getTableList,
    bank_id: bank_id,
    order_number: row.order_number ?? "",
    course_id: course_id ?? "",
    chapter_id: row.chapter_id ?? ""
  };
  editQuestionDrawerRef.value?.acceptParams(params);
};

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  const params: { data: { [question_id: number]: number }; bank_id: number } = { data: {}, bank_id: 0 };
  params.bank_id = Number(bank_id);

  for (let tableDataIndex in proTable.value?.tableData) {
    let question_id = proTable.value?.tableData[Number(tableDataIndex)].question_id;
    params.data[Number(question_id)] = Number(tableDataIndex) + 1;
  }
  sortBankQuestionApi(params);
  // getTableList({});
  proTable.value?.getTableList();
  // proTable.value?.tableData.sort((a, b) => {
  //   return a.order_number - b.order_number;
  // });
  ElMessage.success("修改列表排序成功");
};
</script>
